/*
 * Copyright (c) 2006 - 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * <p>Project: app2022 - FileInputStream1
 * <p>Powered by webrx On 2022-01-18 11:34:02
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class FileInputStream1 {
    public static void main(String[] args) {
        String f = "f.txt";
        try (var fos = new FileOutputStream(f, true); var fis = new FileInputStream(f)) {
            //写入文件
            fos.write("hello\r\nworld\n".getBytes());
            //读取文件
            System.out.println(new String(fis.readAllBytes()));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //使用FileOutputStream FileInputStream实现文件复制功能
        String src = "p.jpg";
        String dst = "p55.jpg";
        try (var fos = new FileOutputStream(dst); var fis = new FileInputStream(src)) {
            //文件比较小可以直接读取所有字节，并复制
            //fos.write(fis.readAllBytes());

            //java9 复制文件功能
            //fis.transferTo(fos);

            //自定义缓冲区大小，来实现复制文件
            byte[] buf = new byte[1024 * 1024];
            int len = 0;
            while ((len = fis.read(buf, 0, buf.length)) >= 0) {
                fos.write(buf, 0, len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
